<template>
  <el-card class="category">
    <el-form :inline="true" :disabled="disabled">
      <el-form-item label="一级分类">
        <el-select
          placeholder="请选择一级分类"
          :modelValue="categoryStore.category1Id"
          @update:modelValue="category1IdChange"
        >
          <el-option
            v-for="c1 in categoryStore.category1List"
            :key="c1.id"
            :label="c1.name"
            :value="c1.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select
          placeholder="请选择二级分类"
          :modelValue="categoryStore.category2Id"
          @update:modelValue="category2IdChange"
        >
          <el-option
            v-for="c2 in categoryStore.category2List"
            :key="c2.id"
            :label="c2.name"
            :value="c2.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select
          placeholder="请选择三级分类"
          v-model="categoryStore.category3Id"
        >
          <el-option
            v-for="c3 in categoryStore.category3List"
            :key="c3.id"
            :label="c3.name"
            :value="c3.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "CategorySelector",
};
</script>

<script lang="ts" setup>
import { onMounted, onBeforeMount } from "vue";
import { useCategoryStore } from "@/stores/category";

defineProps<{
  disabled: boolean;
}>();

const categoryStore = useCategoryStore();

// 1. 一上来请求一级分类数据
onMounted(async () => {
  categoryStore.getCategory1List(); // 发送请求请求一级分类列表，更新pinia数据
});

// 当一级分类id发送变化触发的函数
const category1IdChange = async (category1Id: number) => {
  categoryStore.getCategory2List(category1Id);
};

// 当二级分类id发送变化触发的函数
const category2IdChange = async (category2Id: number) => {
  categoryStore.getCategory3List(category2Id);
};

onBeforeMount(() => {
  categoryStore.category1Id = undefined;
  categoryStore.category2Id = undefined;
  categoryStore.category3Id = undefined;
  categoryStore.category1List = [];
  categoryStore.category2List = [];
  categoryStore.category3List = [];
});
</script>

<style scoped></style>

<style>
.category .el-form-item {
  margin: 10px 20px 10px 0;
}
</style>
